//
//  JCCNet.swift
//  剂查查
//
//  Created by shoubin tao on 2024/12/4.
//  Copyright © 2024 shipin. All rights reserved.
//

import Foundation
import UIKit
let baseUrl = "http://admin.jichacha.vip/api/"

class JCCRespondModel {
    var isSuccess: Bool = true
    var result: Any = []
    var info:String = ""
}
enum JCCRequestType {
    case GET
    case POST
}
class JCCNet {
    
    open class func register (phone:String,password:String,verify:String,completion: @escaping (JCCRespondModel?, Error?) -> Void) {
        request(url: "mobile",requestType: .POST, parameters: ["phone":phone,"password":password,"verify":verify],completion: completion)
    }

    
    open class func getFavoriteList (completion: @escaping (JCCRespondModel?, Error?) -> Void) {
        request(url: "favorite_list",requestType: .GET, parameters: ["page":"1"],completion: completion)
    }
    
    open class func getUserMoney (completion: @escaping (JCCRespondModel?, Error?) -> Void) {
        request(url: "user/money/money",requestType: .GET, parameters: [:],completion: completion)
    }
    
    open class func getApplyMoneyRecord (completion: @escaping (JCCRespondModel?, Error?) -> Void) {
        request(url: "user/money/extract",requestType: .GET, parameters: [:],completion: completion)
    }
    
    open class func getRedBagRecord (completion: @escaping (JCCRespondModel?, Error?) -> Void) {
        request(url: "user/money/balance",requestType: .GET, parameters: [:],completion: completion)
    }
    
    
    open class func getHistoryList (completion: @escaping (JCCRespondModel?, Error?) -> Void) {
        request(url: "history_list",requestType: .GET, parameters: ["page":"1"],completion: completion)
    }
    
    open class func setFavorite (isAdd:Bool,gcodes:[String], completion: @escaping (JCCRespondModel?, Error?) -> Void) {
        let gcode = gcodes.joined(separator: ",")
        request(url: "favorite",requestType: .POST, parameters: ["status":isAdd ?  "0":"1","gcode":gcode],completion: completion)
    }
    
    open class func getScanningDetail (code:String, completion: @escaping (JCCRespondModel?, Error?) -> Void) {
        request(url: "scanning_detail",requestType: .POST, parameters: ["code":code],completion: completion)
    }
    
    open class func deleteHistory (ids:[String], completion: @escaping (JCCRespondModel?, Error?) -> Void) {
        let ids = ids.joined(separator: ",")
        request(url: "history_del",requestType: .POST, parameters: ["ids":ids],completion: completion)
    }
    
    
    
    
    open class func login (phone:String,password:String,completion: @escaping (JCCRespondModel?, Error?) -> Void) {
        request(url: "login",requestType: .POST, parameters: ["phone":phone,"password":password],completion: completion)
    }
    
    open class func applyMoney (money:Int,weixin:String,qrcode_url:String, completion: @escaping (JCCRespondModel?, Error?) -> Void) {
        request(url: "user/extract/cash",requestType: .POST, parameters: ["money":"\(money)","weixin":weixin,"extract_type":"weixin", "qrcode_url":qrcode_url],completion: completion)
    }
    
    
    open class func sendPhoneCode (phone:String,completion: @escaping (JCCRespondModel?, Error?) -> Void) {
        request(url: "verify",requestType: .POST, parameters: ["phone":phone,"scene":"register"],completion:completion)
    }
    open class func uploadImage(image: UIImage, completion: @escaping (JCCRespondModel?, Error?) -> Void){
        guard let imageData = image.jpegData(compressionQuality: 1.0) else {
            print("Failed to convert image to data")
            return
        }
        let url = "\(baseUrl)\("newUpload")"
        var request = URLRequest(url: URL(string: url)!)
        request.httpMethod = "POST"
        request.addValue(JCCTools.token(), forHTTPHeaderField: "Authorization")
        let boundary = UUID().uuidString
        request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
        
        let body = NSMutableData()
        body.append("--\(boundary)\r\n".data(using: .utf8)!)
        body.append("Content-Disposition: form-data; name=\"file\"; filename=\"image.jpg\"\r\n".data(using: .utf8)!)
        body.append("Content-Type: image/jpeg\r\n\r\n".data(using: .utf8)!)
        body.append(imageData)
        body.append("\r\n--\(boundary)--\r\n".data(using: .utf8)!)
        
        request.httpBody = body as Data
        
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
            if let error = error {
                print("Error uploading image: \(error.localizedDescription)")
                return
            }
            
            guard let httpResponse = response as? HTTPURLResponse else {
                print("Invalid response")
                return
            }
            
            // 对返回的数据进行处理（例如解析JSON）
            do {
                // 尝试解析数据
                if let jsonObject = try JSONSerialization.jsonObject(with: data!) as? [String: Any] {
                    let model:JCCRespondModel = JCCRespondModel()
                    model.isSuccess = jsonObject["code"]as?Int == 1
                    let result:Any = jsonObject["data"] as Any
                    if (model.isSuccess == false) {
                        model.info = jsonObject["info"] as! String
                    }
                    model.result = result
                    DispatchQueue.main.async {
                        completion(model, nil)
                    }
                    print("上传图片\n**** url:\(url)\n**** respond:\(jsonObject)\n**** token:\(JCCTools.token())")
                }
            } catch {
                print("JSON handling error: \(error)")
            }
            
            print("Image uploaded successfully with status code: \(httpResponse.statusCode)")
        }
        
        task.resume()
    }

    open class func request (url:String, requestType:JCCRequestType, data:Data = Data(), parameters:[String:String], completion: @escaping (JCCRespondModel?, Error?) -> Void) {
        
        let isPOST = requestType == .POST
        
        let realUrl = "\(baseUrl)\(url)"
        // 将字典转换为JSON数据
        guard let jsonData = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return }
        
        
        // 创建URL组件
        var components = URLComponents(string: realUrl)
        
        // 将参数添加到查询字符串中
        components?.queryItems = parameters.map { URLQueryItem(name: $0.key, value: $0.value) }
        
        // 确保URL是有效的
        guard let GETUrl = components?.url else {
            fatalError("Invalid URL")
        }
        
        
        // 创建URL对象
        guard let POSTUrl = URL(string:  realUrl) else { return }
        
        // 创建URLRequest对象
        var request = URLRequest(url: isPOST ? POSTUrl : GETUrl)
        var type = "";
        if (isPOST){
            type = "POST"
        }else  {
           type = "GET"
        }
        request.httpMethod = type
        var value = "application/json"
        if (isPOST) {
            if (data.isEmpty){
               request.httpBody = jsonData
            }
            else {
                 value = "multipart/form-data"
                 request.httpBody = data
            }
            
        }
        request.setValue(value, forHTTPHeaderField: "Content-Type")
        request.addValue(JCCTools.token(), forHTTPHeaderField: "Authorization")
        // 创建URLSession
        let session = URLSession.shared
        
        // 创建数据任务并启动
        let task = session.dataTask(with: request) { (data, response, error) in
            // 确保没有错误发生
            if let error = error {
                print("Error: \(error)")
                return
            }
            
            // 确保我们得到了数据
            guard let data = data else {
                print("No data in response")
                return
            }
            
            // 对返回的数据进行处理（例如解析JSON）
            do {
                // 尝试解析数据
                if let jsonObject = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
                    let model:JCCRespondModel = JCCRespondModel()
                    model.isSuccess = jsonObject["code"]as?Int == 1
                    let result:Any = jsonObject["data"] as Any
                    if (model.isSuccess == false) {
                        model.info = jsonObject["info"] as! String
                    }
                    model.result = result
                    DispatchQueue.main.async {
                        completion(model, nil)
                    }
                    print("**** url:\( isPOST ? POSTUrl : GETUrl)\n**** params:\(parameters)\n**** respond:\(jsonObject)\n**** token:\(JCCTools.token())")
                }
            } catch {
                print("JSON handling error: \(error)")
            }
        }
        
        // 启动任务
        task.resume()
    }
    


}

